﻿using Microsoft.Practices.Unity.InterceptionExtension;
using Sapit.Base;
using Sapit.Helpers;
using Sapit.Unity.Attributes;

namespace Sapit.Unity
{
    public class CacheHandler<T> : CacheBase<T>, ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn msg;

            Invocation inv = new Invocation() { InvocationTarget = input.Target, Method = input.MethodBase };

            var cache = AttributeHelper.GetAttributeIfPresent<CacheAttribute>(input.MethodBase);
            if (cache != null)
            {
                if (IsInvocationValidInCache(inv, cache.CacheSeconds))
                {
                    msg = input.CreateMethodReturn(GetCachedValue(inv));
                }
                else
                {
                    msg = getNext()(input, getNext);
                    CacheInvocationValue(inv, (T)msg.ReturnValue);
                }
            }
            else
            {
                msg = getNext()(input, getNext);
            }

            return msg;
        }

        public int Order { get; set; }
    }
}
